package cn.studyjava.verify.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.studyjava.verify.common.Const;
import cn.studyjava.verify.common.base.BaseAction;
import cn.studyjava.verify.common.enums.VerifyEnum;
import cn.studyjava.verify.common.result.JsonResult;
import cn.studyjava.verify.model.ImageVerify;
import cn.studyjava.verify.model.vo.AuthVO;
import cn.studyjava.verify.service.IVerifyService;
import cn.studyjava.verify.util.IpUtil;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @author: zsljava
 * @version 1.0.0
 * <p>
 * History:
 * -----------------------------------------------
 * @Date: 2017年10月18日 下午2:31:35
 * @author: zsljava
 * @version 1.0.0
 * @OP: Create
 * -----------------------------------------------
 * </p>
 *
 * @since
 * @see
 */
@Controller
public class VerifyController extends BaseAction{
	
	private Logger log = LoggerFactory.getLogger(VerifyController.class);
	
	@Autowired
	private IVerifyService verifyService;
	
	@GetMapping("")
	public String init(){
		return "/demo";
	}
	
	/**
	 * 
	 * @Title: generateCode
	 * @Description: 获取验证码
	 * @return
	 * @throws Exception
	 * @return: String
	 */
	@RequestMapping("verifycode")
	@ResponseBody
	public JsonResult<ImageVerify> verifycode() throws Exception{
		ImageVerify verifyCode = verifyService.getVerifyCode();
		return buildJsonResult(verifyCode);
	}
	
	/**
	 * 
	 * @Title: verify
	 * @Description: 校验验证码
	 * @param code
	 * @param value
	 * @return
	 * @throws Exception
	 * @return: String
	 */
	@PostMapping("verify")
	@ResponseBody
	public JsonResult<Object> verify(@RequestParam("code")String code, @RequestParam("xvalue") int xvalue,
			@RequestParam("yvalue") int yvalue, @RequestParam("appId") String appId, HttpServletRequest request){
		String newKey = Const.REDIS_ALREADY_PREFIX.concat(code);
		String ip = IpUtil.getIpAddr(request);
		log.debug("参数 appId {}, newKey {}, xvalue {}, yvalue {}, ip {}", appId, newKey, xvalue, yvalue, ip);
		AuthVO auth =  verifyService.verify(appId, newKey, xvalue, yvalue, ip);
		if(auth.getStatus() ==  Const.VERIFY_STATUS_SUCCESS){
			return buildJsonResult(auth);
		}else{
			return buildFialJsonResult(VerifyEnum.getEnumByCode(auth.getReasonCode()), auth);
		}
		
	}
	
}
